<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class UserController extends Controller
{
    public function index(Request $request)
    {
        return view('user');
    }

    public function password(Request $request)
    {
        if ($request->method() == 'GET') {
            return view('password');
        }
        $oldPassword = $request->input('old_password');
        $user = User::query()->where('name', session('username'))->first();
        if (!$user) {
            return $this->message('password', '用户不存在');
        }
        if (!Hash::check($oldPassword, $user->password)) {
            return $this->message('password', '原密码不正确');
        }
        $user->password = $request->input('password');
        $user->save();
        return $this->message('password', '保存成功');
    }

    public function userInfo(Request $request)
    {
        $user = User::query()->where('name', session('username'))->first();
        if ($request->method() == 'GET') {
            return view('user_info', [
                'user' => $user,
            ]);
        }
        $email = $request->input('email');
        $avatar = $request->input('avatar');
        $user = User::query()->where('name', session('username'))->first();
        if (!$user) {
            return $this->message('user_info', '用户不存在');
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        $user->email = $email;
        $user->save();
        return $this->message('user_info','保存成功', [
            'user' => $user,
        ]);
    }

    public function avatar(Request $request)
    {
        $avatar = $request->file('avatar');
        if (!$avatar) {
            return $this->error('请上传头像');
        }
        $user = User::query()->where('name', session('username'))->first();
        if (!$user) {
            return $this->error('用户不存在');
        }
        $path = Storage::putFile('images', $avatar);
        $url = Storage::url($path);
        return $this->ok('上传成功', [
            'url' => $url,
        ]);
    }
}
